//
//  SetViewController.m
//  小汽车
//
//  Created by mill on 15/1/9.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "SetViewController.h"
#import "SetTableViewCell.h"
#import "Singleton.h"
#import "LandViewController.h"
#import "AboutUsViewController.h"
#import "UserDetailModel.h"
@interface SetViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,LandViewControllerDelegate>

@end

@implementation SetViewController
- (void)dealloc
{
    [_tableView release];
    [_tableArray release];
    [_nicname release];
    [_uid release];
    [_profileImage release];
    [_sex release];
    [_registTime release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray arrayWithObjects:@"新浪微博",@"清除缓存",@"版本信息", @"意见反馈", @"关于", nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"设置";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    [self createView];
}
-(void)backAction:(UIButton *)button
{
    [self.delegate changeViewStateUid:self.uid nicname:self.nicname profileImage:self.profileImage sex:self.sex registTime:self.registTime];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [_tableView registerClass:[SetTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [self.view addSubview:_tableView];
    
    [_tableView release];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_tableArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Singleton *share = [Singleton shareInstance];
    SetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.leftLabel.text = [_tableArray objectAtIndex:indexPath.section];
    
    if(indexPath.section == 0){
        if (share.special == NO) {
            cell.rightLabel.text = @"";
        }else if(share.special == YES){
            cell.rightLabel.text = self.nicname;
        }
    }else if(indexPath.section == 1) {
        cell.rightLabel.text = [self sizeCache];
        if ([cell.rightLabel.text isEqualToString:@"0.00MB"]) {
            cell.rightLabel.text = @"";
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        Singleton *share = [Singleton shareInstance];
        if (share.special == NO) {
            LandViewController *land = [[LandViewController alloc] init];
            land.delegate = self;
            [self.navigationController pushViewController:land animated:YES];
            [land release];
        }else{
            UIAlertView *allert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要退出吗" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定退出", nil];
            [allert show];
        }
    }else if (indexPath.section == 1){
        //清除缓存
        dispatch_async(dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
            NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
            NSString *cachesDir = [paths objectAtIndex:0];
            
            NSString *lanou3g = [cachesDir stringByAppendingPathComponent:@"com.lanou3g.---"];
            NSString *fsCachedData = [lanou3g stringByAppendingPathComponent:@"fsCachedData"];
            NSLog(@"fs = %@",fsCachedData);
            if ([[NSFileManager defaultManager] fileExistsAtPath:fsCachedData]) {
                [[NSFileManager defaultManager] removeItemAtPath:fsCachedData error:nil];
            }
            [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
        });
    }else if(indexPath.section == 2){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"已是最新版本" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:0.7];
        [alert release];
    }
    else if(indexPath.section == 3){
        
    }else if(indexPath.section == 4){
        AboutUsViewController *aboutUs = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutUs animated:YES];
        [aboutUs release];
    }
    
}

//声明
- (void)dismissAlert:(UIAlertView *)alert
{
    if(alert){
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
        
    }
}
-(void)changeViewStateUid:(NSString *)uid nicname:(NSString *)nicname profileImage:(NSString *)profileImage sex:(NSString *)sex registTime:(NSString *)registTime
{
    UserDetailModel *model = [[UserDetailModel alloc] init];
    model.uid = uid;
    model.nickname = nicname;
    model.profileImage = profileImage;
    model.registTime = registTime;
    model.sex = sex;
    self.nicname = model.nickname;
    self.uid = model.uid;
    self.profileImage = model.profileImage;
    self.sex = model.sex;
    self.registTime = model.registTime;
    [self.tableView reloadData];
    [model release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    Singleton *share = [Singleton shareInstance];
    if (buttonIndex == 0) {
        share.special = YES;
    }
    if (buttonIndex == 1) {
        _nicname = @"";
        NSIndexSet * nd=[[NSIndexSet alloc]initWithIndex:0];//刷新第1个section
        [_tableView reloadSections:nd withRowAnimation:UITableViewRowAnimationMiddle];
        share.special = NO;
        [self.delegate changeViewStateUid:self.uid nicname:self.nicname profileImage:self.profileImage sex:self.sex registTime:self.registTime];
    }
}


// 计算缓存文件夹大小
- (long)fileSizeForDir:(NSString*)path
{
    long size = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i < [array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic = [fileManager attributesOfItemAtPath:fullPath error:nil];
            size += fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    [fileManager release];
    return size;
    
}
// 计算缓存大小
- (NSString *)sizeCache
{
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    
    NSString *lanou3g = [cachesDir stringByAppendingPathComponent:@"com.lanou3g.---"];
    
    NSString *fsCachedData = [lanou3g stringByAppendingPathComponent:@"fsCachedData"];
    
    long ImageCacheSize = [self fileSizeForDir:fsCachedData];
    long totalSize = ImageCacheSize;
    
    const unsigned int bytes = 1024*1024 ;   //字节数，如果想获取KB就1024，MB就1024*1024
    
    NSString *string = [NSString stringWithFormat:@"%.2fMB",(1.0 *totalSize/bytes)];
    return string;
}

// 清理缓存最后调用的方法
- (void)clearCacheSuccess
{
    [_tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
